//
//  PGCalendarView.m
//  TestCalendar
//
//  Created by Pill Gong on 14-2-17.
//  Copyright (c) 2014年 Pill Gong. All rights reserved.
//

#import "PGCalendarView.h"
#import "UIView+Addtions.h"
#import "EpointDateUtils.h"
#import "LunarCalendar.h"

#import "ScheduleInfo.h"
#import "PGCalendarItem.h"

#define TopViewHeight 80
#define WeekLabelHeight 21
#define NewTopViewHeight (TopViewHeight-WeekLabelHeight)


@interface PGCalendarView () <PGCalendarItemDelegate, UITableViewDataSource, UITableViewDelegate>

@end

@implementation PGCalendarView {
    int currentNum;
    NSDate *selectedDate;
    NSCalendar *calendar;

    int currentMonth;
	int currentYear;
    int currentDay;
    
    PGCalendarItem *selectedItem;
    
    CalendarOrTable calendarOrTable;
    
    BOOL isMonthViewShow;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.backgroundColor = [UIColor orangeColor];
        self.clipsToBounds = YES;
        [self initCalendarValue];
        [self addTopView:frame];
        [self initWithSubviews:frame];
        isMonthViewShow=YES;
    }
    return self;
}

- (void)resetWithToday {
    //edit by wangzhigang at 2014-12-30 15:39
    //desc pc端删除日程后 清空缓存重新加载
    [_dataDic removeAllObjects];
    [self initCurrentValue:[NSDate date]];
    selectedItem = [PGCalendarItem.alloc init];
    selectedItem.itemDate = [NSDate date];
    [self updateTopViewText:InitStyle];
    
    [NSThread detachNewThreadSelector:@selector(fillSubviews) toTarget:self withObject:nil];
}

- (void)resetWithDate:(NSDate *)date {
    //edit by wangzhigang at 2014-12-30 15:39
    //desc pc端删除日程后 清空缓存重新加载
    [_dataDic removeAllObjects];
    [self initCurrentValue:date];
    selectedItem = [PGCalendarItem.alloc init];
    selectedItem.itemDate = date;
    [self updateTopViewText:SelectStyle];
    
    [NSThread detachNewThreadSelector:@selector(fillSubviews) toTarget:self withObject:nil];
}

- (void)fillSubviews {
    [self fillCurrentView];
    [self fillPrevView];
    [self fillNextView];
    dispatch_sync(dispatch_get_main_queue(), ^{
        if (selectedItem) {
            selectedItem.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.8];
            [self itemPressed:selectedItem];
        }
        if (_delegate && [_delegate respondsToSelector:@selector(finishInitCalendarView)]) {
            [_delegate finishInitCalendarView];
        }
    });
}

- (void)initCalendarValue {
    calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [self initCurrentValue:[NSDate date]];
    self.dataDic = [[NSMutableDictionary alloc] initWithCapacity:3];
}

- (void)initCurrentValue:(NSDate *)date {
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *dateParts = [calendar components:unitFlags fromDate:date];
    currentMonth = [dateParts month];
    currentYear = [dateParts year];
    currentDay = [dateParts day];
    selectedItem = nil;
    selectedDate = [NSDate date];
}

- (void)addTopView:(CGRect)frame {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, NewTopViewHeight)];
    [self addSubview:_topView];
    
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _dateLabel.font = [UIFont boldSystemFontOfSize:26];
    
    [_topView addSubview:_dateLabel];
    
    self.chinaCalendar = [[UILabel alloc] initWithFrame:CGRectZero];
    _chinaCalendar.font = [UIFont boldSystemFontOfSize:16];
    [_topView addSubview:_chinaCalendar];
    
    self.todayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_todayBtn setImage:[UIImage imageNamed:@"nav_ic_jin"] forState:UIControlStateNormal];
    [_topView addSubview:_todayBtn];
    
    UIButton* leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(5, _topView.centerY-15, 30, 30);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"calendar_left_btn"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(showPrevView) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* rightBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame=CGRectMake(_topView.right-5-30, _topView.centerY-15, 30, 30);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"calendar_right_btn"] forState:UIControlStateNormal];
    rightBtn.right=_topView.right-5;
    [rightBtn addTarget:self action:@selector(showNextView) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:leftBtn];
    [_topView addSubview:rightBtn];
    
//    [self addWeekLabels:frame];
    [self updateTopViewText:InitStyle];
}

- (void)updateTopViewText:(ChangeStyle)changeStyle {

    NSDate *date;
    switch (changeStyle) {
        case InitStyle:
            date = [NSDate date];
            break;
        case SwipeStyle: {
            if (selectedItem) {
                selectedItem.backgroundColor = [UIColor clearColor];
                selectedItem = nil;
            }
            if (isMonthViewShow) {
                if ([self isDayInTheMonth:[NSDate date]]) {
                    date = [NSDate date];
                } else {
                    date = [self setDateWithYear:currentYear month:currentMonth day:1];
                }
            }else{
                //edit by wangzhigang at 2014-12-31 10:35
                //desc: 日程每日切换修改
                date = [self setDateWithYear:currentYear month:currentMonth day:currentDay];
                selectedItem = [PGCalendarItem.alloc init];
                selectedItem.itemDate = date;
            }
        }
            break;
        case SelectStyle:
            date = selectedItem.itemDate;
            break;
        default:
            break;
    }
    
    _dateLabel.text = [EpointDateUtils convertToCalendarNeedFormat:date];
    [_dateLabel sizeToFit];
    _dateLabel.top = 5;
    _dateLabel.left = _topView.width/2-_dateLabel.width/2;
    
    LunarCalendar *lunarCalendar = [date chineseCalendarDate];
    NSMutableString *chinaDate = [[NSMutableString alloc] initWithString:[lunarCalendar YearHeavenlyStem]];
    [chinaDate appendString:[lunarCalendar YearEarthlyBranch]];
    [chinaDate appendString:[lunarCalendar ZodiacLunar]];
    [chinaDate appendString:@"年"];
    [chinaDate appendString:[lunarCalendar MonthLunar]];
    [chinaDate appendString:[lunarCalendar DayLunar]];
    
    _chinaCalendar.text = chinaDate;
    [_chinaCalendar sizeToFit];
    _chinaCalendar.top = _dateLabel.bottom;
    _chinaCalendar.left = _topView.width/2-_dateLabel.width/2;
}

- (void)addWeekLabels:(CGRect)frame {
    CGFloat eachWidth = frame.size.width/7;
    NSArray *weekStrArray = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
    CGFloat startX = 0;
    for (int i=0; i<weekStrArray.count; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(startX, 0, eachWidth, WeekLabelHeight)];
        label.text = [weekStrArray objectAtIndex:i];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        [_containerView addSubview:label];
        startX += eachWidth;
    }
}

- (void)initWithSubviews:(CGRect)frame {

    calendarOrTable = Calendar;

//    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(AppWidth, NewTopViewHeight, frame.size.width, frame.size.height-NewTopViewHeight)];
//    _tableView.delegate = self;
//    _tableView.dataSource = self;
//    [self addSubview:_tableView];
    
    self.eventList = [[PGEventListView alloc] initWithFrame:CGRectMake(AppWidth, NewTopViewHeight, frame.size.width, frame.size.height-NewTopViewHeight)];
    _eventList.delegate = self;
    [self addSubview:_eventList];
    self.dataArray = [[NSMutableArray alloc] init];
    
    self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0, NewTopViewHeight, frame.size.width, frame.size.height-NewTopViewHeight)];
    [self addSubview:_containerView];
    [self addWeekLabels:frame];
    
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, WeekLabelHeight, frame.size.width, frame.size.height-TopViewHeight)];
    _contentView.clipsToBounds = YES;
    [_containerView addSubview:_contentView];
    
    self.currentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height-TopViewHeight)];
    [_contentView addSubview:_currentView];
    [self fillCurrentView];

    self.prevView = [[UIView alloc] initWithFrame:CGRectMake(0, -frame.size.height+TopViewHeight, frame.size.width, frame.size.height-TopViewHeight)];
    [_contentView addSubview:_prevView];
    [self fillPrevView];

    self.nextView = [[UIView alloc] initWithFrame:CGRectMake(0, frame.size.height-TopViewHeight, frame.size.width, frame.size.height-TopViewHeight)];
    [_contentView addSubview:_nextView];
    [self fillNextView];
    
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeUpGesture:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer:swipeUpGesture];
    
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDownGesture:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self addGestureRecognizer:swipeDownGesture];
    
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeftGesture:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipeLeftGesture];
    
    UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGesture:)];
    swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipeRightGesture];
}

- (void)fillCurrentView {
    int rowNum = [self getRowNumOfMonth:currentMonth andYear:currentYear];
    if (self.currentItemsArr == nil) {
        self.currentItemsArr = [[NSMutableArray alloc] initWithCapacity:42];
    } else {
        [_currentItemsArr removeAllObjects];
    }
    [self drawItemsView:rowNum withItemStyle:CurrentItem];
    [self updateItemsView:CurrentItem];
}

- (void)fillPrevView {
    int month, year;
    year = currentYear;
    if (currentMonth == 1) {
        month = 12;
        year = currentYear-1;
    } else {
        month = currentMonth-1;
    }

    int rowNum = [self getRowNumOfMonth:month andYear:year];
    if (self.prevItemsArr == nil) {
        self.prevItemsArr = [[NSMutableArray alloc] initWithCapacity:42];
    } else {
        [_prevItemsArr removeAllObjects];
    }
    [self drawItemsView:rowNum withItemStyle:PrevItem];
    [self updateItemsView:PrevItem];
}

- (void)fillNextView {
    int month, year;
    year = currentYear;
    if (currentMonth == 12) {
        month = 1;
        year = currentYear+1;
    } else {
        month = currentMonth+1;
    }
    
    int rowNum = [self getRowNumOfMonth:month andYear:year];
    if (self.nextItemsArr == nil) {
        self.nextItemsArr = [[NSMutableArray alloc] initWithCapacity:42];
    } else {
        [_nextItemsArr removeAllObjects];
    }
    [self drawItemsView:rowNum withItemStyle:NextItem];
    [self updateItemsView:NextItem];
}

- (void)drawItemsView:(int)rowNum withItemStyle:(ItemStyle)itemStyle {
    
    UIView *useView;
    NSMutableArray *useItemArr;
    
    switch (itemStyle) {
        case PrevItem: {
            useView = _prevView;
            useItemArr = _prevItemsArr;
        }
            break;
        case CurrentItem: {
            useView = _currentView;
            useItemArr = _currentItemsArr;
        }
            break;
        case NextItem:{
            useView = _nextView;
            useItemArr = _nextItemsArr;
        }
            break;
        default:
            break;
    }
    
    CGFloat itemHeight = _contentView.height / rowNum;
    CGFloat itemWidth = _contentView.width / 7;
    
    for (UIView *v in useView.subviews) {
        [v removeFromSuperview];
    }
    
    
    for (int i = 0; i < rowNum; i++) {
		for(int j = 0; j < 7; j++) {
			CGRect itemFrame = CGRectMake(j*itemWidth, i*itemHeight, itemWidth, itemHeight);
			PGCalendarItem *item = [[PGCalendarItem alloc] initWithFrame:itemFrame];
			item.delegate = self;
			[useItemArr addObject:item];
			[useView addSubview:item];
		}
	}
}

- (void)updateItemsView:(ItemStyle)itemStyle {
    int month, year;
    year = currentYear;

    NSMutableArray *useItemArr;

    switch (itemStyle) {
        case PrevItem: {
            useItemArr = _prevItemsArr;
            if (currentMonth == 1) {
                month = 12;
                year = currentYear-1;
            } else {
                month = currentMonth-1;
            }
        }
            break;
        case CurrentItem: {
            useItemArr = _currentItemsArr;
            month = currentMonth;
        }
            break;
        case NextItem:{
            useItemArr = _nextItemsArr;
            if (currentMonth == 12) {
                month = 1;
                year = currentYear+1;
            } else {
                month = currentMonth+1;
            }
        }
            break;
        default:
            break;
    }
    
    NSArray *monthArray;
    if (itemStyle == CurrentItem) {
        NSString *monthKey = [NSString stringWithFormat:@"%d-%d", year, month];
        monthArray = [_dataDic objectForKey:monthKey];
    }
    
    int weekdayOfFirst = [self getFirstWeekdayOfMonth:month andYear:year];
    int numDaysInMonth = [self getDayNumOfMonth:month andYear:year];
    int rowNum = [self getRowNumOfMonth:month andYear:year];
    int day = 1;
	for (int i = 0; i < rowNum; i++) {
		for(int j = 0; j < 7; j++) {
			int buttonNumber = i * 7 + j;
			if (buttonNumber >= useItemArr.count) {
                break;
            }
			PGCalendarItem *item = [useItemArr objectAtIndex:buttonNumber];
			[item setItemDate:nil];
            item.userInteractionEnabled = NO;
			
			if(buttonNumber >= (weekdayOfFirst - 1) && day <= numDaysInMonth) {
                item.userInteractionEnabled = YES;
				NSDate *itemDate = [self setDateWithYear:year month:month day:day];
                if ([self isSameDay:itemDate date2:[NSDate date]]) {
                    item.isToday = YES;
                }
                if (itemStyle == CurrentItem) {
                    // TODO: get currentDay's event number
                    int eventCount = [self getEventCount:monthArray year:year month:month day:day];
                    item.eventCount = eventCount;
                }
				[item setItemDate:itemDate];
				++day;
			}
		}
	}
}

- (NSDate *)setDateWithYear:(int)year month:(int)month day:(int)day {
    NSDateComponents *dateParts = [[NSDateComponents alloc] init];
    [dateParts setMonth:month];
    [dateParts setYear:year];
    [dateParts setDay:day];
    NSDate *date = [calendar dateFromComponents:dateParts];
    return date;
}

#pragma mark - PGCalendarItemDelegate

- (void)itemPressed:(PGCalendarItem *)item {
//    NSLog(@"item:%@", [item itemDate]);
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
//	[dateFormatter setDateStyle:NSDateFormatterShortStyle];
//	NSString *theDate = [dateFormatter stringFromDate:item.itemDate];
    NSLog(@"theDate:%@", [EpointDateUtils convertToCalendarNeedFormat:item.itemDate]);
    if ([item isEqual:selectedItem]) {
        [self responsePressActionWithOutUIChange];
        return;
    }
    if (selectedItem) {
        selectedItem.backgroundColor = selectedItem.stateColor;
    }
    selectedItem = item;
    [self responsePressActionWithOutUIChange];
}

- (void)responsePressActionWithOutUIChange {
    [self updateTopViewText:SelectStyle];
    
    [self getDataArrayWithItem:selectedItem.itemDate];
    [self showTableView];
}

#pragma mark - PGEventListViewDelegate

- (void)editListItem:(ScheduleInfo *)scheduleInfo {
    if (_delegate && [_delegate respondsToSelector:@selector(editCalendarItem:)]) {
        [_delegate editCalendarItem:scheduleInfo];
    }
}
- (void)delListItem:(ScheduleInfo *)scheduleInfo {
    //删除日程后 清空缓存重新加载
     [_dataDic removeAllObjects];
    if (_delegate && [_delegate respondsToSelector:@selector(delCalendarItem:)]) {
        [_delegate delCalendarItem:scheduleInfo];
    }
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    ScheduleInfo *scheduleInfo = [_dataArray objectAtIndex:indexPath.row];
    cell.textLabel.text = scheduleInfo.Subject;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"SELECT: %d", indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

#pragma mark - up and down gesture

- (void)swipeUpGesture:(UISwipeGestureRecognizer *)swipeGesture {
    NSLog(@"up");
    if (calendarOrTable == Calendar) {
        [self showNextView];
    }
}

- (void)swipeDownGesture:(UISwipeGestureRecognizer *)swipeGesture {
    NSLog(@"down");
    if (calendarOrTable == Calendar) {
        [self showPrevView];
    }
}

- (void)swipeLeftGesture:(UISwipeGestureRecognizer *)swipeGesture {
    NSLog(@"left");
    NSDate *date = [EpointDateUtils convertStr2Date:_dateLabel.text format:@"yyyy.MM.dd"];
    [self getDataArrayWithItem:date];
    [self showTableView];
}

- (void)swipeRightGesture:(UISwipeGestureRecognizer *)swipeGesture {
    NSLog(@"right");
    [self showContainerView];
}

- (void)showOrHiddenBackButton {
    if (_delegate && [_delegate respondsToSelector:@selector(middleViewChanged:)]) {
        [_delegate middleViewChanged:calendarOrTable];
    }
}

- (void)showNextView {
    [self moveUpAnimation:YES];
}

- (void)showPrevView {
    [self moveDownAnimation:YES];
}

- (void)showTableView {
    if (calendarOrTable == Calendar) {
        //edit by wangzhigang at 2014-12-31 10:35
        //desc: 日程每日切换修改
        isMonthViewShow=NO;
        [self moveLeftAnimation:YES];
    }
}

- (void)showContainerView {
    if (calendarOrTable == Table) {
        //edit by wangzhigang at 2014-12-31 10:35
        //desc: 日程每日切换修改
        isMonthViewShow=YES;
        [self moveRightAnimation:YES];
    }
}

- (void)moveUpAnimation:(BOOL)animated {
    
    CGRect tempFrame = _currentView.frame;
    [self updateDate:YES];

    
    [self updateTopViewText:SwipeStyle];
    [UIView animateWithDuration:0.5f animations:^{
        _nextView.frame = tempFrame;
        _currentView.top = _prevView.top;
    } completion:^(BOOL finished) {
        _prevView = _currentView;
        self.prevItemsArr = [[NSMutableArray alloc] initWithArray:_currentItemsArr];
        _currentView = _nextView;
        self.currentItemsArr = [[NSMutableArray alloc] initWithArray:_nextItemsArr];

        _nextView = [[UIView alloc] initWithFrame:CGRectMake(0, tempFrame.size.height, tempFrame.size.width, tempFrame.size.height)];
        [_contentView addSubview:_nextView];
        [self fillNextView];
        if (_delegate && [_delegate respondsToSelector:@selector(currentMonthChanged:)]) {
            [_delegate currentMonthChanged:self];
        }
    }];
}

//edit by wangzhigang at 2014-12-31 10:35
//desc: 日程每日切换修改
-(void)updateDate:(BOOL)isAdd{
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    selectedDate = [EpointDateUtils convertStr2Date:_dateLabel.text format:@"yyyy.MM.dd"];
    NSDateComponents *dateParts = [calendar components:unitFlags fromDate:selectedDate];
    currentMonth = [dateParts month];
    currentYear = [dateParts year];
    currentDay = [dateParts day];
    if(isAdd){
        if (isMonthViewShow) {
            if (currentMonth == 12) {
                currentMonth = 1;
                currentYear++;
            } else {
                currentMonth++;
            }
        }else{
            //每天叠加
            //闰年2月
            if (currentMonth==2&&[self is_leap_year:currentYear]) {
                if (currentDay==29) {
                    currentDay=1;
                    currentMonth++;
                }else{
                    currentDay++;
                }
                
                
                //非闰年2月
            }else if(currentDay==28&&currentMonth==2&&![self is_leap_year:currentYear]){
                if (currentDay==28) {
                    currentDay=1;
                    currentMonth++;
                }else{
                    currentDay++;
                }
                
            }else if(currentMonth==2||currentMonth==4||currentMonth==6||currentMonth==9||currentMonth==11){
                if (currentDay==30) {
                    currentDay=1;
                    currentMonth++;
                }else{
                    currentDay++;
                }
                
            }else if(currentMonth==1||currentMonth==3||currentMonth==5||currentMonth==7||currentMonth==8||currentMonth==10||currentMonth==12){
                if (currentDay==31) {
                    currentDay=1;
                    if (currentMonth == 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                }else{
                    currentDay++;
                }
            }
        }
    }else{
        if (isMonthViewShow) {
            if (currentMonth == 1) {
                currentMonth = 12;
                currentYear--;
            } else {
                currentMonth--;
            }
        }else{
            //每天锐减
            //闰年2月
            if (currentMonth==3&&[self is_leap_year:currentYear]) {
                if(currentDay==1){
                    currentDay = 29;
                    currentMonth--;
                }else{
                    currentDay--;
                }
                
                //非闰年2月
            }else if(currentMonth==3&&![self is_leap_year:currentYear]){
                if(currentDay==1){
                    currentDay = 28;
                    currentMonth--;
                }else{
                    currentDay--;
                }
            }else if(currentMonth==1||currentMonth==2||currentMonth==4||currentMonth==6||currentMonth==8||currentMonth==9||currentMonth==11){
                if(currentDay==1){
                    currentDay = 31;
                    if (currentMonth == 1) {
                        currentMonth = 12;
                        currentYear--;
                    } else {
                        currentMonth--;
                    }
                }else{
                    currentDay--;
                }

            }else if(currentMonth==5||currentMonth==7||currentMonth==10||currentMonth==12){
                
                if(currentDay==1){
                    currentDay = 30;
                    currentMonth--;
                }else{
                    currentDay--;
                }
            }
        }
    }
   
}

-(BOOL) is_leap_year:(int) year{
    if ((year%4==0 && year%100!=0)||year % 400 == 0){
        return YES;
    }else{
        return NO;
    }
}
//end by wangzhigang at 2014-12-31 10:35
//desc: 日程每日切换修改

- (void)moveDownAnimation:(BOOL)animated {
    
    CGRect tempFrame = _currentView.frame;
    [self updateDate:NO];
    [self updateTopViewText:SwipeStyle];
    [UIView animateWithDuration:0.5f animations:^{
        _prevView.frame = tempFrame;
        _currentView.top = _nextView.top;
    } completion:^(BOOL finished) {
        _nextView = _currentView;
        self.nextItemsArr = [[NSMutableArray alloc] initWithArray:_currentItemsArr];
        _currentView = _prevView;
        self.currentItemsArr = [[NSMutableArray alloc] initWithArray:_prevItemsArr];

        _prevView = [[UIView alloc] initWithFrame:CGRectMake(0, -tempFrame.size.height, tempFrame.size.width, tempFrame.size.height)];
        [_contentView addSubview:_prevView];
        [self fillPrevView];
        if (_delegate && [_delegate respondsToSelector:@selector(currentMonthChanged:)]) {
            [_delegate currentMonthChanged:self];
        }
    }];
}

- (void)moveLeftAnimation:(BOOL)animated {
    
//    CGFloat tempX = _tableView.left;
    CGFloat tempX = _eventList.left;
    [UIView animateWithDuration:0.5f animations:^{
        //_tableView.left = _containerView.left;
        _eventList.left = _containerView.left;
        _containerView.left = -tempX;
    } completion:^(BOOL finished) {
        calendarOrTable = Table;
        [self showOrHiddenBackButton];
    }];
}

- (void)moveRightAnimation:(BOOL)animated {
    
    CGFloat tempX = _containerView.left;
    [UIView animateWithDuration:0.5f animations:^{
//        _containerView.left = _tableView.left;
//        _tableView.left = -tempX;
        _containerView.left = _eventList.left;
        _eventList.left = -tempX;
    } completion:^(BOOL finished) {
        calendarOrTable = Calendar;
        [self showOrHiddenBackButton];
    }];
}

#pragma mark - Calendar logic

- (int)getDayNumOfMonth:(int)month andYear:(int)year {
    NSDateComponents *dateParts = [[NSDateComponents alloc] init];
	[dateParts setMonth:month];
	[dateParts setYear:year];
	[dateParts setDay:1];
	NSDate *dateOnFirst = [calendar dateFromComponents:dateParts];

    int numDaysInMonth = [calendar rangeOfUnit:NSDayCalendarUnit
										inUnit:NSMonthCalendarUnit
                                       forDate:dateOnFirst].length;
    return numDaysInMonth;
}

- (int)getFirstWeekdayOfMonth:(int)month andYear:(int)year {
    NSDateComponents *dateParts = [[NSDateComponents alloc] init];
	[dateParts setMonth:month];
	[dateParts setYear:year];
	[dateParts setDay:1];
	NSDate *dateOnFirst = [calendar dateFromComponents:dateParts];

	NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:dateOnFirst];
	int firstWeekday = [weekdayComponents weekday];
    return firstWeekday;
}

- (int)getRowNumOfMonth:(int)month andYear:(int)year {
    int daysNum = [self getDayNumOfMonth:month andYear:year];
    int firstWeekday = [self getFirstWeekdayOfMonth:month andYear:year];
    
    int leftDaysNum = daysNum - (8-firstWeekday);
    int rowNum = leftDaysNum/7;
    rowNum = leftDaysNum%7==0 ? rowNum : ++rowNum;
    return ++rowNum;
}

- (int)getEventCount:(NSArray *)monthArray year:(int)year month:(int)month day:(int)day {
    //[self convertStr2FromStr:_str oldFormat:@"yyyy/M/d H:mm:ss" withNewFormat:@"yyyy/MM/dd"];
    NSString *dateStr = [NSString stringWithFormat:@"%d-%d-%d", year, month, day];
    NSDate *date = [EpointDateUtils convertStr2Date:dateStr format:@"yyyy-M-d"];
    
    int count = 0;
    
    for (ScheduleInfo *scheduleInfo in monthArray) {
        NSString *FromDateStr = [EpointDateUtils convertStr2FromStr:scheduleInfo.FromDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M-d"];
        NSDate *FromDate = [EpointDateUtils convertStr2Date:FromDateStr format:@"yyyy-M-d"];
        
        NSString *ToDateStr = [EpointDateUtils convertStr2FromStr:scheduleInfo.ToDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M-d"];
        NSDate *ToDate = [EpointDateUtils convertStr2Date:ToDateStr format:@"yyyy-M-d"];
        
        if ([self date:date isBetweenDate:FromDate andDate:ToDate]) {
            count++;
        }
    }

    return count;
}

- (NSArray *)getEventArray:(NSArray *)monthArray withDate:(NSDate *)date {
    NSString *dateStr = [EpointDateUtils convertDate2FormatStr:date format:@"yyyy-M-d"];
    NSDate *date2 = [EpointDateUtils convertStr2Date:dateStr format:@"yyyy-M-d"];
    
    NSMutableArray *eventArray = [[NSMutableArray alloc] initWithCapacity:monthArray.count];
    
    for (ScheduleInfo *scheduleInfo in monthArray) {
        NSString *FromDateStr = [EpointDateUtils convertStr2FromStr:scheduleInfo.FromDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M-d"];
        NSDate *FromDate = [EpointDateUtils convertStr2Date:FromDateStr format:@"yyyy-M-d"];
        
        NSString *ToDateStr = [EpointDateUtils convertStr2FromStr:scheduleInfo.ToDateTime oldFormat:@"yyyy-MM-dd HH:mm" withNewFormat:@"yyyy-M-d"];
        NSDate *ToDate = [EpointDateUtils convertStr2Date:ToDateStr format:@"yyyy-M-d"];
        
        if ([self date:date2 isBetweenDate:FromDate andDate:ToDate]) {
            [eventArray addObject:scheduleInfo];
        }
    }
    return eventArray;
}


- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2 {
    
    NSCalendar* tcalendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    
    NSDateComponents* comp1 = [tcalendar components:unitFlags fromDate:date1];
    
    NSDateComponents* comp2 = [tcalendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    
    [comp1 month] == [comp2 month] &&
    
    [comp1 year]  == [comp2 year];
}

- (BOOL)isDayInTheMonth:(NSDate *)date {
    NSCalendar* tcalendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    
    NSDate *monthDate = [self setDateWithYear:currentYear month:currentMonth day:1];
    
    NSDateComponents* comp1 = [tcalendar components:unitFlags fromDate:monthDate];
    
    NSDateComponents* comp2 = [tcalendar components:unitFlags fromDate:date];
    
    return [comp1 month] == [comp2 month] &&
    
    [comp1 year]  == [comp2 year];
}

- (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate {

    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;
    
    if ([date compare:endDate] == NSOrderedDescending)
        return NO;
    
    return YES;
}

#pragma mark - property

- (NSString *)getCurrentYearAndMonth {
    return [EpointDateUtils convertStr2FromStr:_dateLabel.text oldFormat:@"yyyy.MM.dd" withNewFormat:@"yyyy-MM"];
}

- (NSDate *)getCurrentYeartMonthAndDay {
    return [EpointDateUtils convertStr2Date:_dateLabel.text format:@"yyyy.MM.dd"];
}

- (int)getDayNumOfCurrentMonth {
    return [self getDayNumOfMonth:currentMonth andYear:currentYear];
}

- (PGCalendarItem *)getSelectedItem {
    return selectedItem;
}

#pragma mark - data load and update

- (void)dataLoadFinish {
    NSLog(@"dataLoadFinish ...");
    [self updateItemsView:CurrentItem];
    if (calendarOrTable == Table) {
        // TODO: update table data
        [self getDataArrayWithItem:selectedItem.itemDate];
    }
}

- (void)getDataArrayWithItem:(NSDate *)itemDate {
    NSString *monthKey = [NSString stringWithFormat:@"%d-%d", currentYear, currentMonth];
    NSArray *monthArray = [_dataDic objectForKey:monthKey];
    
    NSArray *eventArray = [self getEventArray:monthArray withDate:itemDate];
    [_dataArray removeAllObjects];
    [_dataArray addObjectsFromArray:eventArray];
    _eventList.dataArray = _dataArray;
//    [_tableView reloadData];
    // TODO: reload data _eventList
    [_eventList reloadData];
}

@end
